/**
 * Main application file
 */

'use strict';

// Set default node environment to development
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var express = require('express');
var mongoose = require('mongoose');
var config = require('./config/environment');
var bodyParser = require('body-parser');

var formidable = require('formidable');
var fs = require('fs');
var path = require('path');
var util = require('util');

//配置验证码的基本属性
var ccap = require('ccap')({
    width:130,
    height:36,
    offset:20,
    quality:100,
    fontsize:30
});
var uploadDir = path.join(config.root, 'client/assets/avators');

var session=require('express-session');
var MongoStore=require('connect-mongo')(session);

// Connect to database
if(!config.useMongo){
    mongoose.connect(config.mongo.uri, config.mongo.options);
    mongoose.connection.on('error', function(err) {
        console.error('MongoDB connection error: ' + err);
        process.exit(-1);
      }
    );
    // Populate DB with sample data
    if(config.seedDB) { require('./config/seed'); }
}
// Setup server
var app = express();
var server = require('http').createServer(app);
var socketio = require('socket.io')(server, {
    serveClient: config.env !== 'production',
    path: '/socket.io-client'
});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

app.use(session({
    secret:'huaguo-secret',
    cookie:{
        maxAge:1000*60*30
    },
    store: new MongoStore({
        db: 'huaguo-dev'
    })
}));

app.use('/api/users/login',function(req,res,next){
    if(req.body.captcha.toLowerCase() == req.session.captcha.toLowerCase()){
        next();
    }else{
        res.send({code:0,msg:'验证码有误'});
    }
});

require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);

//图片验证码模块
app.get('/img',function(req,res){
	  var ary = ccap.get();
  	var txt = ary[0];
  	var buf = ary[1];
    req.session.captcha=txt;
  	res.send(buf);
});

//上传个性头像
app.post('/api/avator/upload',function(req,res){
    var form = new formidable.IncomingForm();
    form.encoding = 'utf-8';
    form.uploadDir = uploadDir;
    form.parse(req, function (error, fields, files) {
        if(error){
            console.log(error);
        }else{
            var filename = files.file.name;
            fs.renameSync(files.file.path, uploadDir + '/' + filename);
        }
    });
})


// Start server
server.listen(config.port, config.ip, function () {
    console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});

// Expose app
exports = module.exports = app;
